package dao.util;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;


public class DBConnection {

	private static Properties prop = new Properties();
	private static String url;
	private static String username;
	private static String password;
	private static String driverClass;

	public static Connection connect() {
		Connection connection = null;
		try {
//			String path=DbUtil.class.getClassLoader().getResource("/").getPath();
//			path=path.substring(1,path.indexOf("classes"));
//			prop.load(new FileInputStream(path+"DbConfig.properties"));
//			prop.load(new FileInputStream(DbUtil.class.getClassLoader().getResource("../../DbConfig.properties").getPath()));
			prop.load(new FileInputStream(DBConnection.class.getClassLoader().getResource("user.properties").getPath()));
			url = prop.getProperty("url");
			username = prop.getProperty("username");
			password = prop.getProperty("password");
			driverClass = prop.getProperty("driverClass");
			
			
			Class.forName(driverClass);

			connection = DriverManager.getConnection(url, username, password);
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return connection;
	}

	public static void free(Connection connection, PreparedStatement preparedStatement, ResultSet resultSet) {
		try {
			if (resultSet != null) {
				resultSet.close();
			}
			if (preparedStatement != null) {
				preparedStatement.close();
			}
			if (connection != null) {
				connection.close();
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public static void main(String[] args) {
		System.out.println(DBConnection.connect());
	}
}
